<template>
  <!-- 新增编辑的弹层 -->
  <el-dialog :visible.sync="showDialog" :title="title" :close-on-click-modal="false" @close="closeDialog">
    <!-- 表单内容 -->
    <el-form ref="form" label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="权限启用">
        <el-switch
          v-model="formData.enVisible"
          active-text="启用"
          active-value="1"
          inactive-text="不启用"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="text-align: right;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="btnOK">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermissionApi, getPermissionDetailApi, editPermissionApi } from '@/api/permission'
export default {
  name: 'AddPermission',
  data() {
    return {
      showDialog: false,
      formData: {
        enVisible: '0', // 启用禁用, 0禁用, 1启用
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        type: '', // 类型标记了一级(页面访问权) 二级(按钮操作权)
        pid: '' // 添加到哪个节点下
      },
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑权限' : '新增权限'
    }
  },
  methods: {
    // 打开弹框
    openDialog(type, pid) {
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },
    // 关闭弹框
    closeDialog() {
      this.showDialog = false
      this.formData = {
        enVisible: '0',
        name: '',
        code: '',
        description: '',
        type: '',
        pid: ''
      }
      this.$refs.form.resetFields()
    },
    // 表单提交 => 修改新增逻辑
    async btnOK() {
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      if (this.formData.id) {
        await editPermissionApi(this.formData)
        this.$message.success('修改成功')
      } else {
        await addPermissionApi(this.formData)
        this.$message.success('添加成功')
      }
      this.closeDialog()
      this.$emit('updata')
    },
    // 信息回显
    async getPermissionInfo(id) {
      this.showDialog = true
      const res = await getPermissionDetailApi(id)
      this.formData = res.data
    }
  }
}

</script>

<style>

</style>
